package com.sendinfo.xspring.controller;

import java.io.UnsupportedEncodingException;
import java.lang.reflect.InvocationTargetException;
import java.util.HashMap;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;

import org.apache.commons.beanutils.BeanUtils;

public abstract class BaseController {
	
	protected String base;
	
	/**
	 * 默认分页条数为每页10条
	 */
	protected static final Integer DEFAULT_PAGE_SIZE = 10;
	
	/**
	 * 把request参数封装到VO
	 * @author jianjiang
	 * @param bean
	 * @param request
	 * @throws IllegalAccessException
	 * @throws InvocationTargetException
	 */
	public void populate(Object bean, HttpServletRequest request) throws IllegalAccessException, InvocationTargetException {
		BeanUtils.populate(bean, request.getParameterMap());
    }
	
	/**
	 * 获取参数map
	 * (把HttpServletRequest里的ParameterMap统一转换成HashMap)
	 * @param request
	 * @return
	 */
	@SuppressWarnings("unchecked")
	public Map<String, String> getParamMap(HttpServletRequest request){
		try {
			request.setCharacterEncoding("UTF-8");
		}
		catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		Map<String,String> paramMap = new HashMap<String, String>();
		Map<String,String> reqParamMap = new HashMap<String, String>();
		reqParamMap.putAll(request.getParameterMap());
		for(String key : reqParamMap.keySet()){
			paramMap.put(key, request.getParameter(key));
		}
		return paramMap;
	}

	public String getBase(HttpServletRequest request) {
		int port=request.getServerPort();
		if(port==80){
			return request.getScheme()+"://"+request.getServerName()+request.getContextPath()+"/";
		}else{
			return request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+request.getContextPath()+"/";
		}
	}
	
}
